<!--
 * @Author       : tg
 * @LastEditors  : tg
 * @description  : 组织管理新增/编辑
 * @updateInfo   :
 * @Date         : 2023-10-17 10:05:50
 * @LastEditTime: 2023-10-23 10:10:15
-->
<script lang="ts" setup name="OrganizationModal">
import type { ElTree } from 'element-plus'
import { ikTree } from 'iking-utils'
import type { Ref } from 'vue'
import { useFormRules } from '@g/hooks/use-rules'
import { organizaApi } from '@/MainApp/apis/organiza'
const AddOrgani = defineAsyncComponent(() => import('./AddOrgani.vue'))
const GlCommonGroup = defineAsyncComponent(() => import('./GlCommonGroup/index.vue'))
const router = useRouter()
const route = useRoute()

const { lenPhone, lenShort, lenName, lenLink } = useLength()
const { msgError } = useMessage()
const depChange: Ref<Boolean> | undefined = inject('depChange')
const formKey: { [key: string]: any; } = {
  // 组织名称
  name: '',
  grade: 2, // 级别
  code: '', // 编码
  parentId: route.query.treeId || '', // 父级组织编号
  shortName: '', // 组织简称
  leader: '', // 主管领导
  establishDate: '', // 成立日期
  status: 'ACTIVE', // 成立日期
  shareholdingType: '1', // 股权形式
  address: '', // 详细地址
  website: '', // 网址
  postalCode: '', // 邮编
  phone: '', // 手机号
  fax: '', // 传真号
  introductionType: '1', // 简介类型
  introduction: '', // 简介
  provinceCode: '', // 省
  cityCode: '', // 市
  districtCode: '', // 区
  streetCode: '', //
  tag: [] // 组织标签
}
const depState = reactive({
  title: '新增组织',
  loading: false
})
const form = ref({ ...formKey })
const depRef = ref()
const depRules = useFormRules([
  {
    key: 'name',
    required: true,
    msg: '请输入组织名称',
    trigger: 'blur'
  }, {
    key: 'parentId',
    required: true,
    msg: '请选择上级组织',
    trigger: 'blur'
  }, {
    key: 'phone',
    type: 'telephone',
    required: false,
    msg: '请输入联系电话',
    trigger: 'blur',
    typeMsg: '联系电话格式不正确'
  }])
const handleClose = () => {
  handleBack()
  depState.loading = false
  depRef.value?.resetFields()
  form.value = { ...formKey }
  depState.title = '新增组织'
  depChange!.value = false
}
// 详情接口
const detailData = async (id: any) => {
  const { msg, success, data } = await organizaApi.detailId(id)
  if (success) {
    form.value = {
      ...data,
      city: data.districtCode === '' ? [data.provinceCode, data.cityCode] : [data.provinceCode, data.cityCode, data.districtCode],
      shareholdingType: `${data.shareholdingType}`,
      introductionType: `${data.introductionType}`
    }
  }

  else { msgError(msg) }
}
// tree
const loadingTree = ref(false)
const defaultExpand: Ref<string[]> = ref([])
const depData = ref()

const treeRef = ref<{ tree?: InstanceType<typeof ElTree>;filterText: string; }>()
const getAllDeps = async () => {
  try {
    treeRef.value && (treeRef.value.filterText = '')
  }
  catch (error) {
  }
  loadingTree.value = true
  const { msg, data, success } = await organizaApi.getAllDeps()
  if (success) {
    const fixData = data?.map((li: { name: any; id: any; }) => {
      return {
        ...li,
        label: li.name,
        value: li.id
      }
    })
    depData.value = data
      ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
      : []
    data.forEach((item: any) => {
      if (item.id === route.query.treeId)
        gradeChange(item.grade)
    })
    !defaultExpand.value.length
      && (defaultExpand.value = depData.value.map((d: { id: string; }) => d.id))
  }
  else { msgError(msg) }

  loadingTree.value = false
}
// 行政区域
const provinceCodeList = ref()
// 省级
const cityListData = async () => {
  const { msg, data, success } = await organizaApi.cityList()
  if (success) {
    const fixData = data?.map((li: { name: any; id: any; }) => {
      return {
        ...li,
        label: li.name,
        value: li.id
      }
    })
    provinceCodeList.value = fixData
  }
  else { msgError(msg) }
}

// 初始化
const init = () => {
  // 初始获取
  getAllDeps()
  cityListData()
  if (route.query!.isEditing === 'edit') {
    depState.title = '修改组织'
    detailData(route.query.treeId)
  }
  else {
    depState.title = '新增组织'
  }
}
init()
// 新增、修改
const handConfirm = () => {
  depRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      depState.loading = true
      // const ids: any[] = []
      // form.value.tag.forEach((item: { id: any; }) => {
      //   ids.push(item.id)
      // })
      const _param = {
        ...form.value
        // tag: ids
      }
      const { msg, success } = route.query!.isEditing === 'edit'
        ? await organizaApi.updateOrganiza(_param)
        : await organizaApi.addOrganiza(_param)
      if (success) {
        handleClose()
        depChange!.value = true
      }
      else {
        msgError(msg)
      }
    }
  })
}

const isExpand1 = ref(true) // 基本信息展开收起
const isExpand2 = ref(true) // 更多信息展开收起
// 返回上个页面
const handleBack = () => {
  router.push(
    {
      path: '/system-manage/organization-manage'
    }
  )
}
// 新增标签
const AddOrganiShow = ref(false)
const selectiveUnit = () => {
  AddOrganiShow.value = true
}
// 选择标签
const visibleShowCommonGroup = ref(false)
const addCommonGroup = () => {
  visibleShowCommonGroup.value = true
}
// 选择tree
const handSelect = (data: any) => {
  gradeChange(data.grade)
}
// 处理级别
const gradeChange = (data: any) => {
  form.value.grade = parseInt(data) + 1
}
// 根据父级id获取
const parentIdData = async (id: any) => {
  const { msg, data, success } = await organizaApi.parentId(id)
  if (success) {
    const fixData = data?.map((li: { name: any; id: any; }) => {
      return {
        ...li,
        label: li.name,
        value: li.id
      }
    })
    return fixData
  }
  else { msgError(msg) }
}
const cityCodeList = ref([] as any)
const districtCodeList = ref([] as any)
const streetCodeList = ref([] as any)
// 触发省级
const provinceCodeSelect = (val: any) => {
  form.value.provinceCode = val
  parentIdData(val).then(res => {
    cityCodeList.value = res
  })
}
// 触发市级
const cityCodeSelect = (val: any) => {
  form.value.cityCode = val
  parentIdData(val).then(res => {
    districtCodeList.value = res
  })
}
// 触发区级
const districtCodeSelect = (val: any) => {
  form.value.districtCode = val
  parentIdData(val).then(res => {
    streetCodeList.value = res
  })
}
// 触发街道
const streetCodeSelect = (val: any) => {
  form.value.streetCode = val
}
// 切换简介
const introductionChange = () => {
  form.value.introduction = ''
}
// 取消标签新增
const cancel = () => {
  AddOrganiShow.value = false
}
// 保存标签返回
const listLabel = ref([] as any)
const handConfirmChange = (row: any) => {
  const list: any = []
  list.push(row)
  listLabel.value = listLabel.value.concat(list)
  form.value.tag = listLabel.value.map((item: {
    [x: string]: any
  }) => {
    item.executeOrganizationName = item.name
    item.executeOrganizationId = item.id
    return item
  })
}
// 删除已选组织
const handleCloseTag = (val: number) => {
  form.value.tag.splice(val, 1)
}
// 清空已选择
const clearData = () => {
  form.value.tag = []
}
// 选择标签返回
const handleSelectionChange = (dataList: any) => {
  form.value.tag = dataList.map((item: {
    [x: string]: any
  }) => {
    item.executeOrganizationName = item.name
    item.executeOrganizationId = item.id
    return item
  })
  // userForm.value.executeOrganizationList = dataList
  visibleShowCommonGroup.value = false
}
// 关闭选择标签
const cancelCommonGroup = () => {
  visibleShowCommonGroup.value = false
}
</script>

<template>
  <IkPageMain fixed>
    <IkPageHeader :title="depState.title" :auto-close="true" @back="handleBack" />
    <div class="box">
      <p class="box-base"><GlCard card-title="基本信息" /><GlExpand :is-expand="isExpand1" @handleChangStatus="isExpand1 = !isExpand1" /></p>
      <el-form
        v-if="isExpand1"
        ref="depRef"
        :model="form"
        :rules="depRules"
        label-width="90px"
        style="padding: 20px 0"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="组织名称" prop="name">
              <el-input
                v-model.trim="form.name"
                clearable
                placeholder="请输入组织名称"
                :maxlength="lenName"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="上级组织" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                placeholder="请选择上级组织"
                :data="depData"
                check-strictly
                :render-after-expand="false"
                @node-click="handSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="级别" prop="grade">
              <el-input
                v-model="form.grade"
                disabled
                placeholder="根据上级组织级别，自动回显，回显为：上级组织级别+1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="编码" prop="code">
              <el-input
                v-model.trim="form.code"
                clearable
                placeholder="请输入编码"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="简称" prop="shortName">
              <el-input
                v-model.trim="form.shortName"
                clearable
                placeholder="请输入简称"
                :maxlength="lenName"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="主管领导" prop="leader">
              <IkPersonSelect
                v-model="form.leader"
                clearable
                placeholder="请选择主管领导"
                title="主管领导"
                :multiple="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="成立日期" prop="establishDate">
              <el-date-picker
                v-model="form.establishDate"
                type="date"
                placeholder="请选择成立日期"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="ACTIVE" size="large">启用</el-radio>
                <el-radio label="DEACTIVE" size="large">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <p class="box-base"><GlCard card-title="更多信息" /><GlExpand :is-expand="isExpand2" @handleChangStatus="isExpand2 = !isExpand2" /></p>
      <el-form
        v-if="isExpand2"
        ref="depRef"
        :model="form"
        :rules="depRules"
        label-width="90px"
        style="padding: 20px 0"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="股权形式" prop="shareholdingType">
              <el-radio-group v-model="form.shareholdingType">
                <el-radio label="1" size="large">全资</el-radio>
                <el-radio label="2" size="large">参股</el-radio>
                <el-radio label="3" size="large">控股</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="所在区域" prop="city">
              <!-- <el-cascader
                ref="cascaderItem"
                v-model="form.city"
                placeholder="请选择所在区域"
                style="width:100%"
                :options="cityList"
                check-strictly
                :render-after-expand="false"
              /> -->
              <el-select
                v-model="form.provinceCode"
                placeholder="请选择省级"
                style="width: 24%;margin-right: 10px;"
                @change="provinceCodeSelect"
              >
                <el-option
                  v-for="item in provinceCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="form.cityCode"
                placeholder="请选择市级"
                style="width: 24%;margin-right: 10px;"
                @change="cityCodeSelect"
              >
                <el-option
                  v-for="item in cityCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="form.districtCode"
                placeholder="请选择区/县级"
                style="width: 24%;margin-right: 10px;"
                @change="districtCodeSelect"
              >
                <el-option
                  v-for="item in districtCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="form.streetCode"
                placeholder="请选择街道"
                style="width: 25%"
                @change="streetCodeSelect"
              >
                <el-option
                  v-for="item in streetCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model.trim="form.address"
                clearable
                placeholder="请输入详细地址"
                :maxlength="lenName"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="网址" prop="website">
              <el-input
                v-model.trim="form.website"
                clearable
                placeholder="请输入网址"
                :maxlength="lenLink"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="邮编" prop="postalCode">
              <el-input
                v-model.trim="form.postalCode"
                clearable
                placeholder="请输入邮编"
                maxlength="6"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model.trim="form.phone"
                clearable
                placeholder="请输入联系电话"
                :maxlength="lenPhone"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="传真号" prop="fax">
              <el-input
                v-model.trim="form.fax"
                clearable
                placeholder="请输入传真号"
                :maxlength="lenShort"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="标签">
              <el-button @click="selectiveUnit()">
                <i class="iconfont icon-icon_add" style="margin-right: 5px;font-weight: 600;font-size: 12px;"></i>
                标签
              </el-button>
              <el-button @click="addCommonGroup()">
                <i class="iconfont icon-icon_add" style="margin-right: 5px;font-weight: 600;font-size: 12px;"></i>
                选择标签
              </el-button>
              <p style="padding-left: 20px">
                已选 {{ form.tag?.length > 0 ? form.tag?.length : 0 }} 个标签
                <GlTooltip v-if="form.tag?.length > 0" content="一键清空">
                  <template #content>
                    <i class="iconfont icon-Icon_delete" @click="clearData"></i>
                  </template>
                </GlTooltip>
              </p>
              <GlExecutiveUnit :unit-list="form.tag" :icon-show="false" @handleDeleteTag="handleCloseTag" />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="简介" prop="introductionType">
              <el-radio-group v-model="form.introductionType" @change="introductionChange">
                <el-radio label="1" size="large">手动录入</el-radio>
                <el-radio label="2" size="large">外部链接</el-radio>
                <el-radio label="3" size="large">内部路由</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item prop="introduction">
              <IkTinymce v-if="form.introductionType === '1'" v-model="form.introduction" style="width: 100%" />
              <el-input
                v-else-if="form.introductionType === '2'"
                v-model.trim="form.introduction"
                clearable
                placeholder="请输入外部链接地址"
                :maxlength="lenLink"
                show-word-limit
              />
              <el-input
                v-else
                v-model.trim="form.introduction"
                clearable
                placeholder="请输入内部路由地址"
                :maxlength="lenLink"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bottom-class">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        :loading="depState.loading"
        @click="handConfirm"
      >
        保存
      </el-button>
    </div>
    <!-- 新增标签 -->
    <AddOrgani :visible="AddOrganiShow" @cancel="cancel" @handConfirmChange="handConfirmChange" />
    <!-- // 选择标签 -->
    <!-- dandleSelectionChange" -->
    <GlCommonGroup
      :visible-show="visibleShowCommonGroup"
      @cancel="cancelCommonGroup"
      @handleSelectionChange="handleSelectionChange"
    />
    <!-- <template #footer>
      <el-button
        bg
        text
        @click="handleClose"
      >
        {{ t('action.cancel') }}
      </el-button>
      <el-button
        type="primary"
        :loading="depState.loading"
        @click="handConfirm"
      >
        {{ t('action.sure') }}
      </el-button>
    </template> -->
  </IkPageMain>
</template>

<style lang="scss" scoped>
.box{
  padding: 0 20px;
  overflow: scroll;

  .box-base{
    width: 110px;
    display: flex;
    align-items: baseline;
    justify-content: space-between;
  }
}

.icon-Icon_delete{
  margin-left: 10px;
  font-weight: 600;
  font-size: 14px;
  color: red;
  cursor: pointer;
}

.bottom-class{
  width: 100%;
  display: flex;
  justify-content: end;
  padding: 10px 20px;
  box-sizing: border-box;
}
</style>
